import { pageBlock, saveBlock, updateBlock } from '@/services/api/api-block';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  ModalForm,
  ProColumns,
  ProFormInstance,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, message, Tag } from 'antd';
import { useRef } from 'react';

interface BlockDrawerProps {
  onClose(): void;
}
const BlockDrawer: React.FC<BlockDrawerProps> = ({ onClose }) => {
  const actionRefWord = useRef<ActionType>();
  const formeRefWord = useRef<ProFormInstance>();

  const actionRefCategory = useRef<ActionType>();
  const formeRefCategory = useRef<ProFormInstance>();

  const columns: ProColumns<any>[] = [
    {
      title: '内容',
      dataIndex: 'content',
      width: '90%',
      copyable: true,
      ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <Tag
          color={record.state === 0 ? 'red' : 'green'}
          key="state"
          onClick={async () => {
            record.state = record.state === 0 ? 1 : 0;
            const response = await updateBlock({ ...record });
            if (response.code === 0) {
              action?.reload();
              message.success('提交成功');
            } else {
              message.warning('提交失败');
            }
          }}
        >
          {record.state === 0 ? '禁用' : '开启'}
        </Tag>,
      ],
    },
  ];

  const saveBlockModalForm = (title: string, type: number, label: string) => {
    return (
      <ModalForm<{
        type: number;
        content: string;
      }>
        key="saveBlock"
        title={title}
        trigger={
          <Button type="primary">
            <PlusOutlined />
            新建
          </Button>
        }
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => console.log('run'),
        }}
        submitTimeout={2000}
        onFinish={async (values) => {
          values.type = type; //word
          const response = await saveBlock({ ...values });
          if (response.code === 0) {
            actionRefWord.current?.reload();
            actionRefCategory.current?.reload();
            message.success('提交成功');
          } else {
            message.warning(response.msg);
          }
          return true;
        }}
      >
        <ProFormTextArea
          name="content"
          label={label}
          tooltip="最长为 100 位"
          placeholder="请输入"
        />
      </ModalForm>
    );
  };

  return (
    <DrawerForm<{
      name: string;
      company: string;
    }>
      onOpenChange={(open) => {
        if (!open) {
          onClose();
        }
      }}
      title="屏蔽管理"
      trigger={
        <Button key="block" type="primary" danger>
          屏蔽管理
        </Button>
      }
      submitter={false}
      drawerProps={{
        destroyOnClose: true,
        maskClosable: true,
      }}
      onFinish={async (values) => {
        console.log(values.name);
        // 不返回不会关闭弹框
        return true;
      }}
    >
      <ProTable<any>
        rowKey="id"
        headerTitle="屏蔽标题中的关键字"
        actionRef={actionRefWord}
        formRef={formeRefWord}
        showHeader={false}
        columns={columns}
        request={async (params = {}) => {
          params.type = 1;
          const response = await pageBlock({ ...params });
          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        pagination={{
          pageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        search={{
          optionRender: false,
          collapsed: false,
        }}
        toolbar={{
          search: {
            onSearch: (value: string) => {
              formeRefWord.current?.setFieldsValue({ content: value });
              formeRefWord.current?.submit();
            },
          },
          actions: [saveBlockModalForm('屏蔽标题中的关键字', 1, '需要屏蔽的标题中的关键字')],
        }}
      />
      <ProTable<any>
        rowKey="id"
        headerTitle="屏蔽文章的类型"
        actionRef={actionRefCategory}
        formRef={formeRefCategory}
        showHeader={false}
        columns={columns}
        request={async (params = {}) => {
          params.type = 2;
          const response = await pageBlock({ ...params });
          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        pagination={{
          pageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        search={{
          optionRender: false,
          collapsed: false,
        }}
        toolbar={{
          search: {
            onSearch: (value: string) => {
              formeRefCategory.current?.setFieldsValue({ content: value });
              formeRefCategory.current?.submit();
            },
          },
          actions: [saveBlockModalForm('屏蔽文章的类型', 2, '需要屏蔽文章的类型')],
        }}
      />
    </DrawerForm>
  );
};

export default BlockDrawer;
